package cn.lingyangwl.agile.infra.job.utils;

import cn.lingyangwl.agile.infra.job.constants.*;
import cn.lingyangwl.agile.infra.job.model.entity.*;
import cn.lingyangwl.agile.infra.job.service.*;
import cn.lingyangwl.agile.model.module.tenant.*;
import cn.lingyangwl.agile.tenant.core.utils.*;
import cn.lingyangwl.framework.core.utils.spring.*;
import cn.lingyangwl.framework.log.utils.*;
import com.alibaba.ttl.TransmittableThreadLocal;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.Date;

/**
 * 抽象quartz调用
 *
 * @author shenguangyang
 */
public abstract class AbstractQuartzJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static final TransmittableThreadLocal<Date> threadLocal = new TransmittableThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) {
        JobInfo jobInfo = new JobInfo();
        BeanUtils.copyProperties(context.getMergedJobDataMap().get(JobCons.TASK_PROPERTIES), jobInfo);
        TenantUtils.execute(jobInfo.getTenantId(), () -> {
            try {
                before(context, jobInfo);
                doExecute(context, jobInfo);
                after(context, jobInfo, null);
            } catch (Exception e) {
                log.error("任务执行异常  - ：", e);
                after(context, jobInfo, e);
            }
        });
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param jobInfo  系统计划任务
     */
    protected void before(JobExecutionContext context, JobInfo jobInfo) {
        threadLocal.set(new Date());
        TenantContext.get().setTenantId(jobInfo.getTenantId());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param jobInfo  系统计划任务
     */
    protected void after(JobExecutionContext context, JobInfo jobInfo, Exception e) {
        Date startTime = threadLocal.get();
        threadLocal.remove();

        final JobLog jobLog = new JobLog();
        jobLog.setJobName(jobInfo.getJobName());
        jobLog.setJobGroup(jobInfo.getJobGroup());
        jobLog.setInvokeTarget(jobInfo.getInvokeTarget());
        jobLog.setStartTime(startTime);
        jobLog.setStopTime(new Date());
        long runMs = jobLog.getStopTime().getTime() - jobLog.getStartTime().getTime();
        jobLog.setJobMessage(jobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");
        if (e != null) {
            jobLog.setStatus("1");
            Throwable current = e;
            String traceId = MDCTraceUtils.getTraceId();
            StringBuilder sb = new StringBuilder("traceId: " + traceId);
            while (current != null) {
                sb.append("<br/>").append("[error] ").append(current.getClass().getName()).append(": ").append(current.getMessage());
                current = current.getCause();
            }
            jobLog.setExceptionInfo(sb.toString());
        } else {
            jobLog.setStatus("0");
        }
        jobLog.setJobId(jobInfo.getId());
        jobLog.setTraceId(MDCTraceUtils.getTraceId());

        // 写入数据库当中
        SpringUtils.getBean(IJobLogService.class).save(jobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param jobInfo  系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, JobInfo jobInfo) throws Exception;
}
